package com.jushu.storbox.actions;

import android.content.Context;
import android.content.ContextWrapper;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;

import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.constant.ErrorConstant;
import com.jushu.storbox.service.ICloudDriveService;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.PublicTools;
import com.huawei.sharedrive.sdk.android.common.Constants;
import com.huawei.sharedrive.sdk.android.exception.ClientException;
import com.huawei.sharedrive.sdk.android.modelV2.response.UserResponseV2;
import com.huawei.sharedrive.sdk.android.service.CommonClient;
import com.huawei.sharedrive.sdk.android.serviceV2.CommonClientV2;
import com.huawei.sharedrive.sdk.android.util.StringUtil;

public class Actions extends ContextWrapper {

	private final static String TAG = "Actions";

	protected SharedPreferences settings;

	public Actions(Context context) {
		super(context);
		settings = context.getSharedPreferences(ClientConfig.settings,
				Context.MODE_APPEND);
	}

	/**
	 * @param service
	 * @param userName
	 * @param passWord
	 * @param ihl
	 * @throws ClientException
	 */
	public void smartUpdateAuthiorzation() throws ClientException {
		ShareDriveApplication.getInstance().smartAuthorization();
	}

	/**
	 * 
	 * @param service
	 * @param userName
	 * @param passWord
	 * @param ihl 
	 * @throws ClientException
	 */
	@Deprecated
	protected void loginIn(ICloudDriveService service,
			String userName, String passWord)
			throws ClientException {
		LogUtil.i(TAG, "start loginIn:");
		if (null != service) {
			SharedPreferences settings = getSharedPreferences(
					ClientConfig.settings, Context.MODE_APPEND);
			String oldServerAddress = CommonClient.getInstance().getServiceURL();
			String newServerAddress = settings.getString(ClientConfig.SERVER_ADDRESS, "");
			CommonClient.getInstance().setServiceURL(newServerAddress);
			
			try{
				UserResponseV2 response = service.login(userName, passWord);
				if (null != response) {
					LogUtil.i(TAG, "loginIn success");
					
					if (StringUtil.isBlank(Constants.UAM_ADDRESS) ||  StringUtil.isBlank(ShareDriveApplication.getInstance().getUamAddress())
							|| StringUtil.isBlank(oldServerAddress) || !oldServerAddress.equals(newServerAddress)) {
						setUamAddress(service);
						
					}
					if (StringUtil.isBlank(Constants.UFM_ADDRESS)
							|| StringUtil.isBlank(ShareDriveApplication.getInstance().getUfmAddress())
							|| StringUtil.isBlank(oldServerAddress) || !oldServerAddress.equals(newServerAddress)) {
						setUfmAddress(service);
						
					}
				}else{
					CommonClient.getInstance().setServiceURL(oldServerAddress);
				}
			}catch(ClientException e){
				if(e.getStatusCode() != ErrorConstant.CLIENT_ERROR_LOGIN_INFO) {
					CommonClient.getInstance().setServiceURL(oldServerAddress);
					throw e;
				} else {
					PublicTools.restartApp(getContext());
				}
			}
		} else {
			PublicTools.restartApp(getContext());
		}

	}
	
	public void loginInV2(ICloudDriveService service,
			String userName, String passWord,Handler messageHandler)
			throws ClientException {
		LogUtil.i(TAG, "start loginIn:");
		if (null != service) {
			SharedPreferences settings = getSharedPreferences(
					ClientConfig.settings, Context.MODE_APPEND);
			String oldServerAddress = CommonClient.getInstance().getServiceURL();
			String newServerAddress = settings.getString(ClientConfig.SERVER_ADDRESS, "");
			CommonClient.getInstance().setServiceURL(newServerAddress);
			try{
				UserResponseV2 response = service.login(userName, passWord);

				if (null != response) {
					LogUtil.i(TAG, "loginIn success");
					if (null != messageHandler) {
						LogUtil.i(TAG,
								"loginIn success ihl has value to SENDFROMLOGIN");
						messageHandler.sendEmptyMessage(ClientConfig.SENDFROMLOGIN);
					} else {
						LogUtil.e(TAG, "loginIn success ihl has no value...");
					}
					if (StringUtil.isBlank(Constants.UAM_ADDRESS) ||  StringUtil.isBlank(ShareDriveApplication.getInstance().getUamAddress())
							|| StringUtil.isBlank(oldServerAddress) || !oldServerAddress.equals(newServerAddress)) {
						setUamAddress(service);
						if(messageHandler != null){
							messageHandler.sendEmptyMessage(ClientConfig.SEND_FROM_GET_UAM_ADDRESS);
						}
					}
					if (StringUtil.isBlank(Constants.UFM_ADDRESS)
							|| StringUtil.isBlank(ShareDriveApplication.getInstance().getUfmAddress())
							|| StringUtil.isBlank(oldServerAddress) || !oldServerAddress.equals(newServerAddress)) {
						setUfmAddress(service);
						if(messageHandler != null){
							messageHandler.sendEmptyMessage(ClientConfig.SEND_FROM_GET_UFM_ADDRESS);
						}
					}
				}else{
					CommonClient.getInstance().setServiceURL(oldServerAddress);
				}
			}catch(ClientException e){
				CommonClient.getInstance().setServiceURL(oldServerAddress);
				if(e.getStatusCode() != ErrorConstant.CLIENT_ERROR_LOGIN_INFO) {
					CommonClient.getInstance().setServiceURL(oldServerAddress);
					throw e;
				} else {
					PublicTools.restartApp(getContext());
				}
			}
		} else {
			PublicTools.restartApp(getContext());
		}

	}


	public static void refrshToken(ICloudDriveService service)
			throws ClientException {
		LogUtil.i(TAG, "Start refreshtoken");
		if (service.checkIsRootAndNotify()) {// root
			return;
		}
		service.refreshToken();
	}

	public void loginIn(ICloudDriveService service,
			String userName, String passWord, 
			Handler ehandler, Handler aHandler) {
		if (ShareDriveApplication.getInstance().
				getWifiController().getNetworkState()) {
			LogUtil.i(TAG, "start loginIn:");
			if (null != userName && null != passWord && null != service) {
				SharedPreferences settings = getSharedPreferences(
						ClientConfig.settings, Context.MODE_APPEND);
				String oldServerAddress = CommonClient.getInstance().getServiceURL();
				String newServerAddress = settings.getString(ClientConfig.SERVER_ADDRESS, "");
				CommonClient.getInstance().setServiceURL(newServerAddress);
				
				try{
					UserResponseV2 response = service.login(userName, passWord);
					if (null != response) {
						LogUtil.i(TAG, "loginIn success");
						if (null != aHandler) {
							LogUtil.i(TAG,
									"loginIn success ihl has value to SENDFROMLOGIN");
							aHandler.sendEmptyMessage(ClientConfig.SENDFROMLOGIN);
						} else {
							LogUtil.e(TAG, "loginIn success ihl has no value...");
						}
						if (StringUtil.isBlank(Constants.UAM_ADDRESS) ||  StringUtil.isBlank(ShareDriveApplication.getInstance().getUamAddress())
								|| StringUtil.isBlank(oldServerAddress) || !oldServerAddress.equals(newServerAddress)) {
							setUamAddress(service);
							if(aHandler != null){
								aHandler.sendEmptyMessage(ClientConfig.SEND_FROM_GET_UAM_ADDRESS);
							}
						}
						if (StringUtil.isBlank(Constants.UFM_ADDRESS)
								|| StringUtil.isBlank(ShareDriveApplication.getInstance().getUfmAddress())
								|| StringUtil.isBlank(oldServerAddress) || !oldServerAddress.equals(newServerAddress)) {
							setUfmAddress(service);
							if(aHandler != null){
								aHandler.sendEmptyMessage(ClientConfig.SEND_FROM_GET_UFM_ADDRESS);
							}
						}
					}else{
						CommonClient.getInstance().setServiceURL(oldServerAddress);
					}
				}catch(ClientException e){
					CommonClient.getInstance().setServiceURL(oldServerAddress);
					Message msg = new Message();
					msg.what = e.getStatusCode();
					msg.obj = e;
					ehandler.sendMessage(msg);
				}
			} else {
				PublicTools.restartApp(getContext());
			}
		}
	}

	private void setUamAddress(ICloudDriveService service)
			throws ClientException {
		LogUtil.i(TAG, "set uamaddress:");
		String serverAddress = service.getServerAddress(Constants.UAM);
		ShareDriveApplication.getInstance().setUamAddress(serverAddress);
		CommonClientV2.getInstanceV2().setUAMURL(serverAddress);
	}

	private void setUfmAddress(ICloudDriveService service)
			throws ClientException {
		LogUtil.i(TAG, "start ufmaddress:");
		String serverAddress = service.getServerAddress(Constants.UFM);
		ShareDriveApplication.getInstance().setUfmAddress(serverAddress);
		CommonClientV2.getInstanceV2().setUFMURL(serverAddress);
	}

	public Context getContext() {
		return this;
	}

	public SharedPreferences getSettings() {
		return settings;
	}

	protected boolean checkToken(ICloudDriveService service,Handler exceptionHandler) {
		LogUtil.i(TAG, "checkToken");
		if (ShareDriveApplication.getInstance().
				getWifiController().getNetworkState()) {
			if (PublicTools.isAuthiorzationGotoTimeout(getContext())) {
				try {
					LogUtil.i(TAG, "start loginIn[Actions]");
					loginIn(service,
							PublicTools.getClientUserName(getContext()),
							PublicTools.getClientUserPassFail(getContext()));
					LogUtil.i(TAG, "loginIn_success[Actions]");
				} catch (ClientException e) {
					LogUtil.e(TAG, e);
					if(exceptionHandler != null){
						Message msg = new Message();
						msg.arg1 = ClientConfig.SENDFROMLOGIN;
		                msg.what = e.getStatusCode();
		                exceptionHandler.sendMessage(msg);
					}
					return false;
				}
			}
		}
		return true;
	}

	protected final void executeTask(Runnable runTask) {
		new Thread(runTask).start();
	}
}
